<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'

import type { Socket } from 'socket.io-client'
import { io } from 'socket.io-client'
import { onMounted, onUnmounted, nextTick } from 'vue'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'

import { ref,provide } from 'vue'
import { MsgType } from '@/enums'
import type { Message, TimeMessages } from '@/types/room'

import type { ConsultOrderItem } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'

import { OrderType } from '@/enums' //问诊枚举

import type { Image } from '@/types/consult'

const store = useUserStore()
const route = useRoute()

const list = ref<Message[]>([]) //消息列表
const consult = ref<ConsultOrderItem>() //订单状态
let socket: Socket //socket实例

const initialMsg = ref(true) //首次记录定位

const loadingMsg = ref(false) //下拉刷新
const time = ref(dayjs().format('YYYY-MM-DD hh:mm:ss')) //历史记录时间


// 提供问诊订单数据给后代组件
provide('consult', consult)

// 修改消息状态函数,区分消息是否已经评价
const completeEva = (score: number) => {
  const item = list.value.find((item) => {
    item.msgType === MsgType.CardEvaForm
  })
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
provide('completeEva', completeEva)

// 发送消息
const sendText = (text: string) => {
  // console.log(text, '内容')
  // 发送信息需要  发送人  收消息人  消息类型  消息内容
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: { content: text }
  })
  // console.log('发送')
}

// 发送图片
const sendImage = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: { picture: img }
  })
}

// 挂载
onMounted(async () => {
  // 建立链接，创建 socket.io 实例
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })

  // 检测连接状态
  socket.on('connect', () => {
    // 建立连接成功
    console.log('connect连接成功')
  })

  // 监听连接错误状态
  socket.on('error', (event: any) => {
    // 错误异常消息
    console.log('error错误异常', event)
  })

  // 监听断开状态
  socket.on('disconnect', () => {
    // 已经断开连接
    console.log('disconnect断开连接')
  })

  // 获取默认消息
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    const arr: Message[] = [] // 准备转换常规消息列表
    data.forEach((item, i) => {
      // 标记历史时间，方便历史记录获取
      if (i === 0) {
        time.value = item.createTime
      }
      arr.push({
        msgType: MsgType.Notify,
        msg: { content: item.createTime },
        createTime: item.createTime,
        id: item.createTime
      })
      arr.push(...item.items)
    })
    // 追加到聊天消息列表
    list.value.unshift(...arr)
    // console.log(list, 'list')

    // 聊天记录获取后需要优化用户体验
    loadingMsg.value = false
    if (!arr.length) return showToast('没有更多聊天记录')

    if (initialMsg.value) {
      // 已读消息状态,将此条消息前的消息状态为已读
      socket.emit('updateMsgStatus', arr[arr.length - 1].id)
      // 首次定位到最新消息记录处
      nextTick(() => {
        window.scrollTo(0, document.body.scrollHeight)
        initialMsg.value = false //复位
      })
    }
  })

  // 获取订单状态
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
  // 监听订单状态
  socket.on('statusChange', async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    consult.value = res.data
    console.log(consult.value, '信息')
  })
  // 接收消息
  socket.on('receiveChatMsg', async (event: any) => {
    // 接收情况下需要将信息状态置为已读
    socket.on('updateMsgStatus', event.id)

    list.value.push(event)
    await nextTick()
    window.scrollTo(0, document.body.scrollHeight)
  })
})

// 下拉刷新展示历史记录
const onRefreshMsg = () => {
  // 获取历史记录
  socket.emit('getChatMsgList', 20, time.value, consult.value?.id)
}

// 卸载
onUnmounted(() => {
  // 取消连接
  socket.close()
})
</script>

// 问诊室
<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />
    <!-- 状态栏 -->
    <room-status
      :status="consult?.status"
      :countdown="consult?.countdown"
    ></room-status>
    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="loadingMsg" @refresh="onRefreshMsg">
      <!-- 消息 -->
      <room-message
        v-for="item in list"
        :key="item.id"
        :item="item"
      ></room-message>
    </van-pull-refresh>
    <!-- 操作栏 -->
    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-image="sendImage"
    >
    </room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);

  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
